/*
 * WaveConvert
 * Copyright (c) 2011 Shun Moriya <shun@mnu.sakura.ne.jp>
 *
 * The MIT License
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
 * THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#if !defined(___WAVE_CONVERT_H___)
#define ___WAVE_CONVERT_H___

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>

typedef struct AudioDataHeader
{
	unsigned short flag;
	unsigned char bitsPerSample;
	unsigned char numberChannel;
	unsigned int samplingRate;
	unsigned int size;
	unsigned int loop;
}AudioDataHeader;


class WaveConvert
{
public:
	typedef enum Status
	{
		SUCCESS = 0,
		NOT_RIFF_FORMAT,
		NOT_WAVE_FOMRAT,
		NOT_PCM_FORMAT,
		FILE_SEEK_ERROR,
		FILE_READ_ERROR,
		FILE_WRITE_ERROR,
		NOT_ENOUGH_MEMORY,
	}Status;

public:
	WaveConvert(void);
	~WaveConvert(void);

	Status convert(FILE* out, FILE* in);

private:
	unsigned char *get_bytes(FILE *f, int n)
	{
		static unsigned char s[16];

		assert (n <= sizeof s);
		if (fread(s, n, 1, f) != 1) {
			fprintf(stderr, "Read error\n");
			exit(1);
		}
		return s;
	}

	unsigned long get_ulong(FILE *f)
	{
		unsigned char *s = get_bytes(f, 4);
		return s[0] + 256LU * (s[1] + 256LU * (s[2] + 256LU * s[3]));
	}

	unsigned get_ushort(FILE *f)
	{
		unsigned char *s = get_bytes(f, 2);
		return s[0] + 256U * s[1];
	}
};

#endif
